﻿using Microsoft.EntityFrameworkCore;
using PesticideManage.API.Data;
using PesticideManage.API.Services.Identity.RoleAggregate;
using PesticideManage.API.Services.Menus;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Serialization;

namespace PesticideManage.API.Services.Identity.UserAggregate;

public sealed class UserDTO
{
    public string Name { get; init; } = string.Empty;
    public string MobileNumber { get; init; } = string.Empty;
    public string SmsVCode { get; init; } = string.Empty;
    public string Password { get; set; } = string.Empty;
}
/// <summary>
/// 用户可修改部件
/// </summary>
public class UserModifiablePart : Entity
{
    [StringLength(11)]
    public string? MobileNumber { get; set; }
    [StringLength(255)]
    public string? Email { get; set; }
    [StringLength(255)]
    public Address? Address { get; set; }
}
[Index(nameof(Name), IsUnique = true)]
public class User : UserModifiablePart
{
    private static readonly MD5 _md5 = MD5.Create();
    public User()
    {

    }
    public User(int id)
    {
        Id = id;
    }
    public User(int id, string password) : this(id)
    {
        Password = password;
    }

    [StringLength(20)]
    [MinLength(5, ErrorMessage = "不能小于5个字符")]
    public string Name { get; init; } = string.Empty;
    /// <summary>
    /// 身份证
    /// </summary>
    public ID? IDCard { get; set; }

    /// <inheritdoc cref="Enterprise"/>
    public Enterprise? Enterprise { get; set; }

    public ICollection<Role> Roles { get; set; } = null!;

    [NotMapped]
    public IEnumerable<Menu>? Menus => Roles?.SelectMany(r => r.Menus).Distinct().OrderBy(m => m.Order);

    //private string _password = string.Empty;

    //[JsonIgnore]
    //public string Password { get => _password; set => _password = EncryptPassword(value); }
    [StringLength(32)]
    [JsonIgnore]
    public string Password { get; private set; } = null!;
    public void SetPassword(string password)
    {
        Password = EncryptPassword(password);
    }
    /// <summary>
    /// 加密字符串
    /// </summary>
    /// <param name="password"></param>
    /// <returns></returns>
    private static string EncryptPassword(string password)
    {
        byte[] passwordAndSaltBytes = Encoding.UTF8.GetBytes(password);
        byte[] hs = _md5.ComputeHash(passwordAndSaltBytes);
        return Convert.ToHexString(hs);
        //var sb = new StringBuilder();
        //foreach (var b in hs)
        //{
        //    sb.Append(b.ToString("x2"));
        //}
        //return sb.ToString();
    }
    public bool VerifyPassword(string target)
    {
        return Password == EncryptPassword(target);
    }
}
